<?php
/**
 * 消息API.
 *
 * @author Medz Seven <lovevipdsw@vip.qq.com>
 **/
class UsertokenApi extends Api
{
    
    /**
     * 获取用户信息.
     *
     * @return array
     *
     * @author Medz Seven <lovevipdsw@vip.qq.com>
     **/
    public function getUserInfo()
    {
    	
        $oauth_token = $_REQUEST['oauth_token'];

        if (!$oauth_token) {
            $this->error(array(
                'status' => '-1',
                'msg'    => '没有传入oauth_token',
            ));
        } 
        
        //$userlogin=model('login')->where("oauth_token='".$oauth_token."'")->find();
        $userlogin=M()->query("select * from ".C('DB_PREFIX')."login where oauth_token='".$oauth_token."'");
        if(!$userlogin) {
            $this->error(array(
                'status' => '-2',
                'msg'    => '用户未登录',
            ));
        }
        $uid=$userlogin[0]['uid'];
        $user = model('User')->getUserInfo($uid);
        //个人空间隐私权限
        $privacy = model('UserPrivacy')->getPrivacy($this->mid, $value['uid']);

        return array(
            'status'        => '1',
            'uid'           => $userlogin[0]['uid'],
            'uname'         => $user['uname'],
            'remark'        => $user['remark'],
            'avatar'        => $user['avatar_original'],
            'intro'         => $user['intro'] ? formatEmoji(false, $user['intro']) : '',
            'space_privacy' => $privacy['space'],
        );
    }


	/********** 登录注销 **********/

    /**
     * 认证方法 --using.
     *
     * @param varchar login 手机号或用户名
     * @param varchar password 密码
     *
     * @return array 状态+提示
     */
    public function authorize()
    {
        $_REQUEST = array_merge($_GET, $_POST);

        if (!empty($_REQUEST['login']) && !empty($_REQUEST['password'])) {
            $username = addslashes($_REQUEST['login']);
            $password = addslashes($_REQUEST['password']);

            $map = "(phone = '{$username}' or uname='{$username}' or email='{$username}') AND is_del=0";

            //根据帐号获取用户信息
            $user = model('User')->where($map)->field('uid,password,login_salt,is_audit,is_active')->find();

            //判断用户名密码是否正确
            if ($user && md5(md5($password).$user['login_salt']) == $user['password']) {
                if (model('DisableUser')->isDisableUser($user['uid'])) {
                    return array('status' => 0, 'msg' => '您的帐号被已管理员禁用');
                }
                //如果未激活提示未激活
                if ($user['is_audit'] != 1) {
                    return array('status' => 0, 'msg' => '您的帐号尚未通过审核');
                }
                if ($user['is_active'] != 1) {
                    return array('status' => 0, 'msg' => '您的帐号尚未激活,请进入邮箱激活');
                }

                //记录token
                $data['oauth_token'] = getOAuthToken($user['uid']);
                $data['oauth_token_secret'] = getOAuthTokenSecret();
                $data['uid'] = $user['uid'];
                $login = D('')->table(C('DB_PREFIX').'login')->where('uid='.$user['uid']." AND type='location'")->find();
                if (!$login) {
                    $savedata['type'] = 'location';
                    $savedata = array_merge($savedata, $data);
                    D('')->table(C('DB_PREFIX').'login')->add($savedata);
                } else {
                    //清除缓存
                    model('Cache')->rm($login['oauth_token'].$login['oauth_token_secret']);
                    D('')->table(C('DB_PREFIX').'login')->where('uid='.$user['uid']." AND type='location'")->save($data);
                }

                $data['status'] = 1;

                return $data;
            } else {
                return array('status' => 0, 'msg' => '用户名或密码错误');
            }
        } else {
            return array('status' => 0, 'msg' => '用户名或密码不能为空');
        }
    }

    /**
     * 注销帐号，刷新token --using.
     *
     * @param varchar login 手机号或用户名
     *
     * @return array 状态+提示
     */
    public function logout()
    {
        $login = $this->data['login'];
        $login = addslashes($login);

        $where = '`is_del` = 0 AND (`uid` = \'__LOGIN__\' OR `phone` = \'__LOGIN__\' OR `email` = \'__LOGIN__\' OR `uname` = \'__LOGIN__\')';
        $where = str_replace('__LOGIN__', $login, $where);

        //判断密码是否正确
        $user = model('User')->where($where)->field('uid')->find();
        if ($user) {
            $data['oauth_token'] = getOAuthToken($user['uid']);
            $data['oauth_token_secret'] = getOAuthTokenSecret();
            $data['uid'] = $user['uid'];
            D('')->table(C('DB_PREFIX').'login')->where('uid='.$user['uid']." AND type='location'")->save($data);

            return array('status' => 1, 'msg' => '退出成功');
        } else {
            return array('status' => 0, 'msg' => '退出失败');
        }
    }
	
	
	/**
     * 注册上传头像 --using.
     *
     * @return array 状态值+提示信息
     */
    public function register_upload_avatar()
    {
        $dAvatar = model('Avatar');
        $res = $dAvatar->upload(true);

        return $res;
    }
	
	
    /**
     * 以用户名方式注册.
     *
     * 
     * @param varchar uname 用户名
     * @param varchar password 密码
     * @param varchar avatar_url 头像地址
     * 
     *
     * @return array
     *
     * @author Medz Seven <lovevipdsw@vip.qq.com>
     *
     * @link http://medz.cn
     **/
    public function regurl()
    {
        //上传头像
    	$imgupload=$this->register_upload_avatar();
		//return $imgupload;exit;
		$regmodel = model('Register');
        $registerConfig = model('Xdata')->get('admin_Config:register');
		
		
        $uname = t($_POST['uname']);
        $sex = 2;
        $password = t($_POST['password']);
		$intro=t($_POST['intro']);

        $avatar['picurl'] = $imgupload['data']['picurl'];
        $avatar['picwidth'] = $imgupload['data']['picwidth'];
        $avatar['picheight'] = $imgupload['data']['picheight'];

       
        //用户名验证
        if (!$regmodel->isValidName($uname)) {
            $msg = $regmodel->getLastError();
            $return = array('status' => 0, 'msg' => $msg);
			//判断，如果用户名已经存在，则登录
			if($msg=="\u8be5\u7528\u6237\u540d\u5df2\u7ecf\u5b58\u5728" || $msg=="该用户名已经存在"){
				$_POST['login'] = $uname;
                return $this->authorize();
			}
            return $return;
        }
        //密码验证
        if (!$regmodel->isValidPasswordNoRepeat($password)) {
            $msg = $regmodel->getLastError();
            $return = array('status' => 0, 'msg' => $msg);

            return $return;
        }
        //开始注册
        $login_salt = rand(11111, 99999);
        $map['uname'] = $uname;
        $map['sex'] = $sex;
        $map['login_salt'] = $login_salt;
        $map['password'] = md5(md5($password).$login_salt);
        $map['ctime'] = time();
        $map['is_audit'] = $registerConfig['register_audit'] ? 0 : 1;
        // $map['is_audit'] = 1;
        $map['is_active'] = 1; //手机端不需要激活
        $map['is_init'] = 1; //手机端不需要初始化步骤
        $map['first_letter'] = getFirstLetter($uname);
        $map['intro'] = $intro;
        if (preg_match('/[\x7f-\xff]+/', $map['uname'])) {    //如果包含中文将中文翻译成拼音
            $map['search_key'] = $map['uname'].' '.model('PinYin')->Pinyin($map['uname']);
        } else {
            $map['search_key'] = $map['uname'];
        }
        $uid = model('User')->add($map);
        if ($uid) {
            //第三方登录数据写入
            if (isset($this->data['type'])) {
                $other['oauth_token'] = addslashes($this->data['access_token']);
                $other['oauth_token_secret'] = addslashes($this->data['refresh_token']);
                $other['type'] = addslashes($this->data['type']);
                $other['type_uid'] = addslashes($this->data['type_uid']);
                $other['uid'] = $uid;
                M('login')->add($other);
            }
            // 添加至默认的用户组
            $userGroup = empty($registerConfig['default_user_group']) ? C('DEFAULT_GROUP_ID') : $registerConfig['default_user_group'];
            model('UserGroupLink')->domoveUsergroup($uid, implode(',', $userGroup));
            // 添加双向关注用户
            $eachFollow = $registerConfig['each_follow'];
            if (!empty($eachFollow)) {
                model('Follow')->eachDoFollow($uid, $eachFollow);
            }
            // 添加默认关注用户
            $defaultFollow = $registerConfig['default_follow'];
            $defaultFollow = array_diff(explode(',', $defaultFollow), explode(',', $eachFollow));
            if (!empty($defaultFollow)) {
                model('Follow')->bulkDoFollow($uid, $defaultFollow);
            }

            //保存头像
            if ($avatar['picurl'] && $avatar['picwidth'] && $avatar['picheight']) {
                $dAvatar = model('Avatar');
                $dAvatar->init($uid);
                $data['picurl'] = $avatar['picurl'];
                $data['picwidth'] = $avatar['picwidth'];
                $scaling = 5;
                $data['w'] = $avatar['picwidth'] * $scaling;
                $data['h'] = $avatar['picheight'] * $scaling;
                $data['x1'] = $data['y1'] = 0;
                $data['x2'] = $data['w'];
                $data['y2'] = $data['h'];
                $dAvatar->dosave($data, true);
            }

            if ($map['is_audit'] == 1) {
            	$_POST['login'] = $uname;
                return $this->authorize();
// 				$return = array('status'=>1, 'msg'=>'注册成功', 'need_audit'=>0);
            } else {
                $return = array('status' => 1, 'msg' => '注册成功，请等待审核', 'need_audit' => 1);
            }

            return $return;
        } else {
            $return = array('status' => 0, 'msg' => '注册失败');

            return $return;
        }
    }

	//发布队伍帖子
	public function weiba_fabu()
    {
    	//$this->error('2');
        if (!CheckPermission('weiba_normal', 'weiba_post')) {
            $this->error('对不起，您没有权限进行该操作！');
        }
        $weibaid = intval($this->data['weiba_id']);
        if (!$weibaid) {
            $this->error('请选择队伍！');
        }
        $weiba = D('weiba')->where('weiba_id='.$weibaid)->find();
        if (!CheckPermission('core_admin', 'admin_login')) {
            switch ($weiba['who_can_post']) {
                case 1:
                    $map['weiba_id'] = $weibaid;
                    $map['follower_uid'] = $this->mid;
                    $res = D('weiba_follow')->where($map)->find();
                    if (!$res && !CheckPermission('core_admin', 'admin_login')) {
                        $this->error('对不起，您没有发帖权限，请关注该队伍！');
                    }
                    break;
                case 2:
                    $map['weiba_id'] = $weibaid;
                    $map['level'] = array(
                            'in',
                            '2,3',
                    );
                    $weiba_admin = D('weiba_follow')->where($map)->order('level desc')->field('follower_uid')->findAll();
                    if (!in_array($this->mid, getSubByKey($weiba_admin, 'follower_uid')) && !CheckPermission('core_admin', 'admin_login')) {
                        $this->error('对不起，您没有发帖权限，仅限管理员发帖！');
                    }
                    break;
                case 3:
                    $map['weiba_id'] = $weibaid;
                    $map['level'] = 3;
                    $weiba_admin = D('weiba_follow')->where($map)->order('level desc')->field('follower_uid')->find();
                    if ($this->mid != $weiba_admin['follower_uid'] && !CheckPermission('core_admin', 'admin_login')) {
                        $this->error('对不起，您没有发帖权限，仅限队长发帖！');
                    }
                    break;
            }
        }
        $this->data['content'] = $this->data['content'];
		
//      if (!empty($imgs)) {
//          foreach ($imgs as $v) {
//              $src = getImageUrlByAttachId($v['attach_id'], 320, 1000);
//              $src && $img_arr[] = '<img src="'.$src.'" class="mobile_upload" _src="'.getImageUrlByAttachId($v['attach_id']).'" />';
//          }
//
//          $this->data['content'] = implode(' ', $img_arr).$this->data['content'];
//      }

//      $checkContent = str_replace('&nbsp;', '', $this->data['content']);
//      $checkContent = str_replace('<br />', '', $checkContent);
//      $checkContent = str_replace('<p>', '', $checkContent);
//      $checkContent = str_replace('</p>', '', $checkContent);
//      $checkContents = preg_replace('/<img(.*?)src=/i', 'img', $checkContent);
//      $checkContents = preg_replace('/<embed(.*?)src=/i', 'img', $checkContents);
		$checkContents =$this->data['content'];
        if (strlen(t($this->data['title'])) == 0) {
            $this->error('帖子标题不能为空');
        }
        if (strlen($checkContents) == 0) {
            $this->error('帖子内容不能为空');
        }
		
//      preg_match_all('/./us', t($this->data['title']), $match);
//      if (count($match[0]) > 20) { // 汉字和字母都为一个字
//          $this->error('帖子标题不能超过20个字');
//      }
//      if ($this->data['attach_ids']) {
//          $attach = explode('|', $this->data['attach_ids']);
//          foreach ($attach as $k => $a) {
//              if (!$a) {
//                  unset($attach[$k]);
//              }
//          }
//          $attach = array_map('intval', $attach);
//          $data['attach'] = serialize($attach);
//      }
        $data['weiba_id'] = $weibaid;
        $data['title'] = t($this->data['title']);
        $data['content'] = h($this->data['content']);
        //$data['title'] = $this->data['title'];
       // $data['content'] = $this->data['content'];
        //return $data['content'];
        // 格式化emoji
//      $data['title'] = formatEmoji(true, $data['title']);
//      $data['content'] = formatEmoji(true, $data['content']);

        // 处理换行，临时解决方案
//      $br = array("\r\n", "\n", "\r");
//      $replace = '<br/>';
//      $data['content'] = str_replace($br, $replace, $data['content']);

        $data['post_uid'] = $this->mid;
        $data['post_time'] = $this->data['post_time'];
        //$data['post_time'] = time();
        $data['last_reply_uid'] = $this->mid;
        $data['last_reply_time'] = $data['post_time'];

        $filterTitleStatus = filter_words($data['title']);
        if (!$filterTitleStatus['status']) {
            $this->error($filterTitleStatus['data'], true);
        }
        $data['title'] = $filterTitleStatus['data'];

        $filterContentStatus = filter_words($data['content']);
        if (!$filterContentStatus['status']) {
            $this->error($filterContentStatus['data'], true);
        }
        $data['content'] = $filterContentStatus['data'];
		//return $filterContentStatus;exit;
        $data['from'] = $this->data['from'] ? intval($this->data['from']) : '0';
        $res = D('weiba_post')->add($data);
		//return $res;exit;
        if ($res) {
            D('weiba')->where('weiba_id='.$data['weiba_id'])->setInc('thread_count');
            // 同步到微博
            // $feed_id = D('weibaPost')->syncToFeed($res,$data['title'],t($checkContent),$this->mid);
            $feed_id = model('Feed')->syncToFeed('weiba', $this->mid, $res);
            D('weiba_post')->where('post_id='.$res)->setField('feed_id', $feed_id);
            // $this->assign('jumpUrl', U('weiba/Index/postDetail',array('post_id'=>$res)));
            // $this->success('发布成功');

            $result['id'] = $res;
            $result['feed_id'] = $feed_id;
            // 添加积分
            model('Credit')->setUserCredit($this->mid, 'publish_topic');

            return array(
                    'status'  => 1,
                    'post_id' => $res,
                    'title' => $data['title'],
                    'msg'     => '发布成功',
            );
        } else {
            $this->error('发布失败'.$data['title']);
        }
    }

}
